package com.leonne.harpacristabrasileira.tools;

import java.lang.reflect.Method;
import java.util.ArrayList;

import org.json.JSONArray;

import com.leonne.harpacristabrasileira.activities.FirstPageActivity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;

public class CustomWaitDialog extends AsyncTask<Void, Void, Void>{
	
	protected ProgressDialog dialog;
	protected Activity parentActivity;
	protected String mMethod;
	protected String callback;
	protected boolean showDialog;
	
	/**
	 * Construtor da classe
	 * 
	 * @param activity Referência à classe responsável por disparar esta thread
	 * 
	 * @param mMethod String contendo o nome do método que será chamado em background
	 */
	public CustomWaitDialog(Activity activity, String mMethod, String callback, boolean showDialog) {
		this.parentActivity = activity;
		this.mMethod = mMethod;
		this.callback = callback;
		this.showDialog = showDialog;
	}

	/**
	 * (non-Javadoc)
	 * 
	 * @see android.os.AsyncTask#doInBackground()
	 */
	@Override
	protected Void doInBackground(Void... params) {
		Method method;
		try {
			method = parentActivity.getClass().getMethod(this.mMethod, null);
			method.invoke(this.parentActivity, null);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;		
	}

	/**
	 * (non-Javadoc)
	 * 
	 * @see android.os.AsyncTask#onPreExecute()
	 */
	@Override
	protected void onPreExecute() {
		if (this.showDialog)
			dialog = ProgressDialog.show(parentActivity, "Aguarde...", "Aguarde enquanto os dados são carregados...");
	}

	/**
	 * (non-Javadoc)
	 * 
	 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
	 */
	@Override
	protected void onPostExecute(Void v) {
		Method method;
		try { // Chama o método callback presente na activity pai.
			if (this.callback != null && !this.callback.equals("")){
				method = parentActivity.getClass().getMethod(this.callback, null);
				method.invoke(this.parentActivity, null);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (this.showDialog)
			this.dialog.dismiss();
	}

}
